//
//  WmcSettingVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/1.
//

import UIKit
import YPBedrock
import RxRelay
import YPGraphicEngine

// MARK: - WmcCameraSettingVC + WmcNavigatorProtocol

extension WmcCameraSettingVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.cameraSetting]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        let vm = WmcCameraSettingVM()
        let vc = WmcCameraSettingVC(vm)
        return vc
    }
}

// MARK: - WmcCameraSettingVC + WmcVMProtocol

extension WmcCameraSettingVC: WmcVMProtocol {
    typealias VMType = WmcCameraSettingVM
}

// MARK: - [WmcCameraSettingVC]

class WmcCameraSettingVC: WmcBaseVC {
    
    typealias Action = WmcSettingHeaderView.Action
    typealias DelayTime = WmcSettingHeaderView.DelayTime
    typealias AspectRatio = YPGESunglasses.AspectRatio
    /// 阴影遮罩
    private lazy var maskView: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.wmc_blackH1_000000.withAlphaComponent(0.5)
        return button
    }()
    /// 内容控件
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.wmc_gray_F7F8FA
        return view
    }()
    
    lazy var tableView: UITableView = {
        // 统一注册
//        var registers: [YPRegister] = [
//            YPRegister(WmcCameraSettingCell.self),
//        ]
//        if let regis = cameraSettingDelegate?.tableViewRegisterCell(.current) {
//            registers += regis
//        }
        // tb
        let tableView = UITableView.YP.Create(style: .grouped,
                                              delegate: self,
                                              dataSource: self)
        tableView.wmc_register(cellClasses: [WmcSettingSwitchItemCell.self,
                                             WmcSettingSubTitleSwitchItemCell.self,
                                             WmcSettingContentItemCell.self,
                                             WmcSettingTipContentItemCell.self,
                                             WmcSettingSubTitleActionSwitchItemCell.self
                                            ])
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.tableHeaderView = headerView
        tableView.tableFooterView = footerView
        return tableView
    }()
    
    /// table header view
    private lazy var headerView: WmcSettingHeaderView = {
        let width = contentW - 2.0 * hMargin
        let view = WmcSettingHeaderView(width: width)
        let height = view.fittedHeight()
        view.yp.set(height: height)
        return view
    }()
    /// table footer view
    private lazy var footerView: UIView = {
        let view = UIView()
        view.yp.set(height: 60.0.wmc_autoHor)
        let label = UILabel()
        label.font = 15.wmc_scaleFont()
        label.textColor = UIColor.wmc_BAC1CC
        label.textAlignment = .center
        label.text = "蜀ICP备17030551号-20A"
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        return view
    }()
    
    /// 外部设置的代理
    var cameraSettingDelegate: WmcCameraSettingDelegate? {
        return YPWmcManager.shared.uiDelegate.cameraSettingDelegate
    }

    /// 代理的组
    var de_groupCount: Int {
        return cameraSettingDelegate?.numberOfSections(.current, in: tableView) ?? 0
    }
    
    /// 内容宽度
    private let contentW = 300.0.wmc_autoHor
    /// 水平间距
    private let hMargin = 12.0.wmc_autoHor
    /// 动画时长
    private let animateDuration: TimeInterval = 0.25
    /// 延时拍照时间
    var delayTime: DelayTime = .none {
        didSet {
            headerView.delayTime = delayTime
        }
    }
    /// 画幅比例
    var aspectRatio: AspectRatio = .ar_4_3 {
        didSet {
            headerView.aspectRatio = aspectRatio
        }
    }
    /// 功能模式
    var functionMode: WmcButtonItemType.HomeFunctionMode = .photo {
        didSet {
            headerView.functionMode = functionMode
        }
    }
    /// 视频清晰度
    var articulation: YPGEVideoBuffer.Articulation = ._720p {
        didSet {
            headerView.articulation = articulation
        }
    }
    
    weak var targetVC: UIViewController?
    
    var lifeCycleCalled: Bool = false
    
    let headerAction: PublishRelay<Action> = .init()
    /// 二维码验证开关变化
    let switchChanged: PublishRelay<(WmcButtonItemType.CameraSettingCell, Bool)> = .init()

    
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.loadList()
        // 驱动方法衔接
        YPWmcDrivingManager.shared.cameraSetting_reloadTableDataBlock = { [weak self] in
            guard let weakSelf = self else { return }
            YPGCD.Main { // 谁知道外部调用驱动时候是哪个线程呢
                weakSelf.tableView.reloadData()
            }
        }
        // 如果已登录,获取公众号关注状态
        if WmcLoginManager.shared.isLogin {
            viewModel.getWechatFollowState()
        }
    }


    
    override func makeUI() {
        super.makeUI()
//        makeNavView(showShadow: false)
//        title = "相机设置"
//
//        addSubview(tableView)
//        tableView.snp.makeConstraints { make in
//            make.top.equalTo(navView.snp.bottom)
//            make.left.right.bottom.equalToSuperview()
//        }
        view.backgroundColor = UIColor.clear
        // 阴影遮罩
        view.addSubview(maskView)
        maskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        // contentView
        view.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(-contentW)
            make.top.bottom.equalToSuperview()
            make.width.equalTo(contentW)
        }
        // tableView
        contentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(Wmc_statusBarHeight)
            make.left.equalToSuperview().offset(hMargin)
            make.right.equalToSuperview().offset(-hMargin)
            make.bottom.equalToSuperview()
        }
    }
    
    // MARK: Bind Action
    
    override func bindViewAction() {
        super.bindViewAction()
        // 点击阴影
        maskView.rx.tap.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.hide()
        }).disposed(by: rx.disposeBag)
        // 点击headerview上按钮
        headerView.buttonAction.subscribe(onNext: {
            [weak self] action in
            guard let self = self else { return }
            self.handleHeader(action: action)
        }).disposed(by: rx.disposeBag)
    }

    // MARK: Bind VM
    override func bindViewModel() {
        viewModel.dataListRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
        }).disposed(by: rx.disposeBag)
        // 获取公众号关注状态
        viewModel.followStateGot.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.headerView.isSubscribed = self.viewModel.followState?.isSubscribe ?? false
        }).disposed(by: rx.disposeBag)
        // 点击拍摄辅助线
        viewModel.assistLineItemClicked.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            var actions: [YPBedrockLib.AlertAction] = []
            for cas in WmcHomeControlAssistLineLayer.AssistLineStyle.allCases {
                let action: YPBedrockLib.AlertAction = .init(title: cas.info.name, actionBlock: { [weak self] _ in
                    guard let weakSelf = self else { return }
                    weakSelf.viewModel.updateAssistLineStyle(cas)
                })
                actions.append(action)
            }
            actions.append(.CancelAction(title: "取消"))
            let alert = UIAlertController.YP.Create(title: "辅助线类型", actions: actions, style: .actionSheet)
            self.present(alert, animated: true)
        }).disposed(by: rx.disposeBag)
        // 刷新页面
        viewModel.reloadData.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.tableView.reloadData()
        }).disposed(by: rx.disposeBag)
        // 开关状态变化
        viewModel.switchChanged.bind(to: self.switchChanged).disposed(by: rx.disposeBag)
    }

    /// 是否是自己组
    func isSelfGroup(_ section: Int) -> Bool {
        // 输入组数量
        return section == 0 || section > de_groupCount
    }

    /// 转换为自己组
    func transformSelfSection(_ section: Int) -> Int {
        if section == 0 || de_groupCount == 0 {
            return section
        } else {
            return section - de_groupCount
        }
    }

    /// 转换为自己组
    func transformSelfIndexPath(_ indexPath: IndexPath) -> IndexPath {
        return .init(row: indexPath.row, section: transformSelfSection(indexPath.section))
    }

    /// 转换为代理组
    func transformThisSection(_ section: Int) -> Int {
        if de_groupCount == 0 {
            return 0
        } else {
            return section - 1
        }
    }

    /// 转换为代理组
    func transformDeIndexPath(_ indexPath: IndexPath) -> IndexPath {
        return .init(row: indexPath.row, section: transformThisSection(indexPath.section))
    }
    
    // MARK: Public
    /// 显示页面
    func show(in targetVC: UIViewController) {
        self.targetVC = targetVC
        let nav = WmcNavVC(rootViewController: self)
        nav.modalPresentationStyle = .overFullScreen
        if self.lifeCycleCalled {
            targetVC.beginAppearanceTransition(false, animated: true)
//            targetVC.viewWillDisappear(true)
        }
        targetVC.present(nav, animated: false) {
            if self.lifeCycleCalled {
//                targetVC.viewDidDisappear(true)
                targetVC.endAppearanceTransition()
            }
            self.contentView.snp.updateConstraints { make in
                make.left.equalToSuperview()
            }
            UIView.animate(withDuration: self.animateDuration) {
                self.view.layoutIfNeeded()
            }
        }
    }
    /// 隐藏页面
    func hide(completion: (() -> Void)? = nil) {
        contentView.snp.updateConstraints { make in
            make.left.equalToSuperview().offset(-contentW)
        }
        if self.lifeCycleCalled {
//            self.targetVC?.viewWillAppear(true)
            self.targetVC?.beginAppearanceTransition(true, animated: true)
        }
        UIView.animate(withDuration: animateDuration) {
            self.view.layoutIfNeeded()
        } completion: { _ in
            self.dismiss(animated: false) {
                if self.lifeCycleCalled {
//                    self.targetVC?.viewDidAppear(true)
                    self.targetVC?.endAppearanceTransition()
                }
                completion?()
            }
        }
    }
    
    // MARK: Private
    /// 处理headerView的点击事件
    private func handleHeader(action: Action) {
        switch action {
        case .aspect: // 拍照画幅
            hide {
                [weak self] in
                guard let self = self else { return }
                self.headerAction.accept(action)
            }
        case .delay: // 延时拍照
            headerAction.accept(action)
        case .resolution: // 分辨率
            headerAction.accept(action)
        case .articulation: // 清晰度
            headerAction.accept(action)
        case .invite: // 邀请朋友
            WmcNavigatorManager.push(.invitation)
        case .album: // 团队相册
            WmcNavigatorManager.push(.myTeam)
        case .joinGroup:
            let isLogin = WmcLoginManager.checkLogin(successed: {
                [weak self] in
                guard let self = self else { return }
                self.viewModel.getWechatFollowState()
            })
            if isLogin {
                // 打开微信小程序
                openWXMiniProgram()
            }
        }
    }
    
    /// 打开微信小程序,关注公众号
    private func openWXMiniProgram() {
        WmcShareManager.followWechat()
    }
}

// MARK: UITableViewDelegate

extension WmcCameraSettingVC: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 是否是自己组
        if isSelfGroup(indexPath.section) { // 自己组
            let indexPath = transformSelfIndexPath(indexPath)
            if let group = viewModel.dataListRelay.value.yp.object(at: indexPath.section),
               let item = group.items.yp.object(at: indexPath.row) {
                item.selectedAction?(item)
            }
        } else { // 别组，回调
            if let action = cameraSettingDelegate?.tableView(.current,
                                                             tableView: tableView,
                                                             didSelectRowAt: transformDeIndexPath(indexPath))
            {
                action.transactionDefaultCase { }
            }
        }
    }
}

// MARK: UITableViewDataSource

extension WmcCameraSettingVC: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        var count = viewModel.dataListRelay.value.count
        // 合并组
        if let groupCount = cameraSettingDelegate?.numberOfSections(.current, in: tableView) {
            count += groupCount
        }
        return count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 是否是自己组
        if isSelfGroup(section) { // 自己组
            if let group = viewModel.dataListRelay.value.yp.object(at: transformSelfSection(section)) {
                return group.items.count
            }
        } else {
            return cameraSettingDelegate?.tableView(.current,
                                                    tableView: tableView,
                                                    numberOfRowsInSection: transformThisSection(section)) ?? 0
        }
        return 0
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        // 是否是自己组
        if isSelfGroup(section) { // 自己组
            return 8
        } else {
            return cameraSettingDelegate?.tableView(.current,
                                                    tableView: tableView,
                                                    heightForHeaderInSection: transformThisSection(section)) ?? 8
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        // 是否是自己组
        if isSelfGroup(section) { // 自己组
            let headerView = UIView()
            headerView.backgroundColor = .wmc_grayH19_F5F5F5
            return headerView
        } else {
            return cameraSettingDelegate?.tableView(.current,
                                                    tableView: tableView,
                                                    viewForHeaderInSection: transformThisSection(section))
        }
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        // 是否是自己组
        if isSelfGroup(section) { // 自己组
            return .YP.Min
        } else {
            return cameraSettingDelegate?.tableView(.current,
                                                    tableView: tableView,
                                                    heightForFooterInSection: transformThisSection(section)) ?? 8
        }
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        // 是否是自己组
        if isSelfGroup(section) { // 自己组
            return nil
        } else {
            return cameraSettingDelegate?.tableView(.current,
                                                    tableView: tableView,
                                                    viewForFooterInSection: transformThisSection(section))
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 是否是自己组
        if isSelfGroup(indexPath.section) { // 自己组
            let indexPath = transformSelfIndexPath(indexPath)
            if let group = viewModel.dataListRelay.value.yp.object(at: indexPath.section),
               let item = group.items.yp.object(at: indexPath.row) {
                return item.rowHeight
            }
        } else {
            return cameraSettingDelegate?.tableView(.current,
                                                    tableView: tableView,
                                                    heightForRowAt: transformDeIndexPath(indexPath)) ?? 0
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 是否是自己组
        if isSelfGroup(indexPath.section) { // 自己组
            let group = viewModel.dataListRelay.value[indexPath.section]
            let item = group.items[indexPath.row]
            let cell = tableView.wmc_dequeueReusableCell(cellClass: item.cellClass, for: indexPath)
            cell.item = item
            return cell
        } else if let cell = cameraSettingDelegate?.tableView(.current,
                                                              tableView: tableView,
                                                              cellForRowAt: transformDeIndexPath(indexPath)) {
            // 输入组
            return cell
        }
        return UITableViewCell()
    }
}
